package com.example.myapplication.ContentTest;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.view.ContentInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.example.myapplication.ArrayAdapterInclude.ContactArrayListAdapter;
import com.example.myapplication.R;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;

public class ContactsModifyFragment extends Fragment {

  private ArrayList<ContactInfo> contactInfoList ;
  private static final int MY_PERMISSIONS_REQUEST_WRITE_CONTACTS = 1;
  private View view;
  TextInputLayout nameLayout;
  TextInputLayout numberLayout;
  EditText nameText;
  EditText numberText;

  ListView infoList;

  public ContactsModifyFragment() {

  }

  @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Init();
  }

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (ContextCompat.checkSelfPermission(this.getContext(), Manifest.permission.WRITE_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(this.getActivity(),new String[]{Manifest.permission.WRITE_CONTACTS},
          MY_PERMISSIONS_REQUEST_WRITE_CONTACTS);

    }
  }

  private void Init() {
    Button saveButton = (Button) view.findViewById(R.id.save_button);
    Button showInfoButton = (Button) view.findViewById(R.id.info_button);
    nameLayout = (TextInputLayout) view.findViewById(R.id.name_layout);
    numberLayout = (TextInputLayout) view.findViewById(R.id.number_layout);
    nameText = (EditText) view.findViewById(R.id.name_text);
    numberText = (EditText) view.findViewById(R.id.number_text);
    infoList = (ListView) view.findViewById(R.id.info_list);
    infoList.setVisibility(View.INVISIBLE);

    saveButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_CONTACTS)
            != PackageManager.PERMISSION_GRANTED) {
          // 如果权限未被授予，则请求权限
          ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_CONTACTS},
              MY_PERMISSIONS_REQUEST_WRITE_CONTACTS);
        } else {
          // 权限已经被授予，执行写入联系人信息的操作
          System.out.println("已被授予");

          try {
            SaveContact();
          } catch (RemoteException e) {
            throw new RuntimeException(e);
          } catch (OperationApplicationException e) {
            throw new RuntimeException(e);
          }
        }

        //SaveContact();
      }
    });

    showInfoButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        FindContactInfo();
      }
    });

  }

  private void FindContactInfo() {
    String numStr = String.valueOf(numberText.getText());
    if (!CheckInputText(numStr, numberLayout)) {
      Toast.makeText(getContext(), "请按照提示输入信息", Toast.LENGTH_SHORT);
      return;
    }
    ArrayList<ContactInfo> contactInfoArrayList = GetContactList(numStr);
    if (contactInfoArrayList.size() == 0) {
      Toast.makeText(getContext(), "没有这个联系人", Toast.LENGTH_SHORT);
      return;
    }

    ContactArrayListAdapter adapter =
        new ContactArrayListAdapter(getContext(), contactInfoArrayList);
    infoList.setAdapter(adapter);
    infoList.setVisibility(View.VISIBLE);

  }

  private void SaveContact() throws RemoteException, OperationApplicationException {
    String nameStr = String.valueOf(nameText.getText());
    String numberStr = String.valueOf(numberText.getText());
    if (CheckInputText(nameStr, nameLayout) && CheckInputText(numberStr, numberLayout)) {
      AddContact(nameStr, numberStr);
      //AddContactByContract(nameStr, numberStr);


    } else {
      Toast.makeText(getContext(), "请按照提示输入信息", Toast.LENGTH_SHORT).show();

    }
  }

  private boolean CheckInputText(String str, TextInputLayout layout) {
    if (str.isEmpty()) {
      layout.setError("输入不能为空");
      return false;
    }
    layout.setError(null);
    return true;
  }

  private ArrayList<ContactInfo> GetContactList(String phoneNumber) {
    ArrayList<ContactInfo> infoArrayList = new ArrayList<>();
    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    String[] projection = {
        ContactsContract.Contacts._ID,
        ContactsContract.Contacts.DISPLAY_NAME,
        ContactsContract.CommonDataKinds.Phone.NUMBER
    };
    //查询字符串
    String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE?";
    String[] selectionArgs = { "%" + phoneNumber + "%" };
    ContentResolver resolver = getContext().getContentResolver();
    Cursor cursor = resolver.query(uri, projection, selection, selectionArgs, null);
    if (cursor != null) {
      while (cursor.moveToNext()) {
        @SuppressLint("Range") long contactId =
            cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
        //获取联系人号码
        @SuppressLint("Range") String contactName =
            cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        @SuppressLint("Range") String number =
            cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        ContactInfo contact = new ContactInfo(contactName, number);
        infoArrayList.add(contact);
      }
      cursor.close();
    }
    return infoArrayList;
  }

  @Nullable @Override
  public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.contact_modify_fragment_layout, container, false);
    return view;
  }
  @SuppressLint("Range") private long GetRawID(ContentResolver contentResolver,long nameId) {
    Cursor cursor = contentResolver.query(
        ContactsContract.Data.CONTENT_URI,
        new String[] {ContactsContract.Data.RAW_CONTACT_ID},
        ContactsContract.Data._ID + " = ?",
        new String[] {String.valueOf(nameId)},
        null
    );
    long id = -1;
    if (cursor != null && cursor.moveToFirst()) {
      id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
      cursor.close();
    }
    return id;
  }

  private void AddContactByContract(String nameStr, String numberStr) {

    ContentValues values = new ContentValues();
    ContentResolver resolver = getContext().getContentResolver();
    //插入新的RawContacts条目
    Uri rawContactUri = resolver.insert(ContactsContract.RawContacts.CONTENT_URI, values);
    long rawContactId = ContentUris.parseId(rawContactUri);

    values.clear();
    values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
    values.put(ContactsContract.Data.MIMETYPE,
        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
    values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, nameStr);

    //插入联系人的FirstName数据
    resolver.insert(ContactsContract.Data.CONTENT_URI, values);



    //创建一个新的ContentValue对象，设置联系人的手机号码
    values.clear();
    values.put(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID, rawContactId);
    values.put(ContactsContract.Data.MIMETYPE,
        ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
    values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, numberStr);
    values.put(ContactsContract.CommonDataKinds.Phone.TYPE,
        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
    //插入联系人的手机号码数据
    resolver.insert(ContactsContract.Data.CONTENT_URI, values);

    Toast.makeText(getContext(),"插入成功",Toast.LENGTH_SHORT).show();
  }
  private void AddContact(String name,String number) throws RemoteException, OperationApplicationException {
    //使用事务添加联系人
    Uri uri=Uri.parse("content://com.android.contacts/raw_contacts");
    Uri dataUri = Uri.parse("content://com.android.contacts/data");
    ContentResolver resolver = getContext().getContentResolver();
    ArrayList<ContentProviderOperation> operations = new ArrayList<>();
    ContentProviderOperation op1 =
        ContentProviderOperation.newInsert(uri).withValue("account_name", null).build();
    operations.add(op1);

    //姓名 号码 邮编
    ContentProviderOperation op2 =
        ContentProviderOperation.newInsert(dataUri)
            .withValueBackReference("raw_contact_id", 0)
            .withValue("mimetype", "vnd.android.cursor.item/name")
            .withValue("data2", name)
            .build();
    operations.add(op2);
    ContentProviderOperation op3 =
        ContentProviderOperation.newInsert(dataUri)
            .withValueBackReference("raw_contact_id", 0)
            .withValue("mimetype", "vnd.android.cursor.item/phone_v2")
            .withValue("data1", number)
            .withValue("data2", "2")
            .build();
    operations.add(op3);

    ContentProviderOperation op4 =
        ContentProviderOperation.newInsert(dataUri)
            .withValueBackReference("raw_contact_id", 0)
            .withValue("mimetype", "vnd.android.cursor.item/email_v2")
            .withValue("data1", "1058161932@qq.com")
            .withValue("data2", "2").
            build();
    operations.add(op4);

    //将上述内容添加到手机联系人中
    resolver.applyBatch("com.android.contacts", operations);
    Toast.makeText(getContext(), "添加成功", Toast.LENGTH_SHORT).show();
  }

  @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
      @NonNull int[] grantResults) {
    if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_CONTACTS) {
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // 权限被授予，执行写入联系人信息的操作
        try {
          SaveContact();
        } catch (RemoteException e) {
          throw new RuntimeException(e);
        } catch (OperationApplicationException e) {
          throw new RuntimeException(e);
        }
      } else {
        // 权限被拒绝，显示一个提示或执行相应的操作
        Toast.makeText(getContext(), "需要授予写入联系人信息的权限才能保存联系人", Toast.LENGTH_SHORT).show();
      }
    }
  }
}
